/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.edu.fatec.ads.util;


import java.nio.ByteBuffer;
import javassist.bytecode.ByteArray;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * @author Bruno Moura
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory = null;
    private static Session session = null;
    private static final Logger logger = Logger.getLogger(HibernateUtil.class.getName());

    static{
        try{
            logger.info("Inicio - criacao Session");

            sessionFactory = new AnnotationConfiguration()
                                    .configure()
                                        .buildSessionFactory();

            logger.info("Fim - criacao Session");

        }catch(Throwable cause){
            logger.error("Problemas na criação da sessão!", cause);

            throw new ExceptionInInitializerError(cause);
        }
    }

    /**
     *
     * @return
     * @throws HibernateException
     */
    public static Session getSession()
           throws HibernateException{

        if(session == null){
            session = sessionFactory.openSession();
        }

        return session;
    }

    /**
     *
     */
    public static void closeSession(){
        HibernateUtil.getSession().close();
    }

    /**
     *
     * @return
     */
    public static Session beginTransaction(){
        HibernateUtil.getSession().beginTransaction();

        return HibernateUtil.getSession();
    }

    /**
     *
     */
    public static void commitTransaction(){
        HibernateUtil.getSession().getTransaction().commit();
    }

    /**
     *
     */
    public static void rollbackTransaction(){
        HibernateUtil.getSession().getTransaction().rollback();
    }

}